package com.dkd.common.utils;
import com.dkd.common.enums.UpdateType;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.function.BiConsumer;
import java.util.function.Function;
public class EbUtils {
    public static <T> void setUserIdIfNull(T object, Function<T, Long> getUserId, BiConsumer<T, Long> setUserId) {
        if (getUserId.apply(object) == null) {
            Long userId = SecurityUtils.getUserId();
            setUserId.accept(object,
                    userId);
        }
    }
    public static <T> void setCreateByIfNull(T object, Function<T, String> getCreateBy, BiConsumer<T, String> setCreateBy) {
        if (getCreateBy.apply(object) == null) {
            String userName = SecurityUtils.getUsername();
            setCreateBy.accept(object,
                    userName);
        }
    }
    //更新表的四个字段 createdBy,createdTime,updatedBy,updatedTime
    public static void updateTableFields(UpdateType updateType, Object object) {
        try {
            Class<?> clazz = object.getClass();
            switch (updateType) {
                case ADD_FIELD:
                    Method setCreatedBy = clazz.getMethod("setCreateBy",
                            String.class);
                    setCreatedBy.invoke(object,
                            SecurityUtils.getUsername());
                    Method setCreatedTime = clazz.getMethod("setCreateTime",
                            Date.class);
                    setCreatedTime.invoke(object,
                            new Date());
                    break;
                case UPDATE_FIELD:
                    Method setUpdateBy = clazz.getMethod("setUpdateBy",
                            String.class);
                    setUpdateBy.invoke(object,
                            SecurityUtils.getUsername());
                    Method setUpdateTime = clazz.getMethod("setUpdateTime",
                            Date.class);
                    setUpdateTime.invoke(object,
                            new Date());
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
